//
//  VECreatAssionDTViewController.m
//  VEMoneyPorject
//
//  Created by BlueWind on 2018/9/24.
//  Copyright © 2018年 陈建. All rights reserved.
//

#import "VECreatAssionDTViewController.h"
#import "VECreatDTSummaryTableViewCell.h"
#import "VECreatDTImageTableViewCell.h"
#import "VEAssionModel.h"


#import <TZImageManager.h>
#import <TZVideoPlayerController.h>
#import <TZPhotoPreviewController.h>
#import <TZGifPhotoPreviewController.h>
#import <TZImagePickerController.h>
#import <AssetsLibrary/AssetsLibrary.h>

#import "VEAssociationViewController.h"
#import "PPHTTPRequest.h"


#define KChoicePicCount 9  //最多选择多少张照片
#define KLineShowPicCount 3 //每一行显示多少张照片

@interface VECreatAssionDTViewController ()

@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

@property (nonatomic, strong) NSMutableArray *photoImages;

@property (nonatomic, strong) VEAssionModel *model;

@end

@implementation VECreatAssionDTViewController

{
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
    NSArray * _seletedImgArr;
    UIImage * _nomalImg;
    
    UIButton * _rigthButton;
    
    NSString *_assionId;
    NSString *_summary;
    BRPlaceholderTextView * _inputTextView;

}

- (void)viewDidLoad {
    self.view.backgroundColor = [UIColor whiteColor];
    self.isSuccessNet = YES;
    _selectedPhotos = [NSMutableArray array];
    _selectedAssets = [NSMutableArray array];
    _nomalImg = [UIImage imageNamed:@"c照片添加"];
    _seletedImgArr = @[_nomalImg];
    self.photoImages = [NSMutableArray new];
    
    
    [self setItem];
    
}

- (void)setItem {
    
    self.navigationController.navigationBar.tintColor = [UIColor redColor];
    [self cj_setUpNavRightItemTitle:@"保存" handle:^(NSString *rightItemTitle) {
        
        [self clickDoneItem];
    }];
}

- (void)clickDoneItem {
    
    NSString *str = [_inputTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if ([CJUIKit isNilOrNull:str]) {
        [CJUIKit showErrorWithStatus:@"请输入描述"];
    }else if ([CJUIKit isNilOrNull:self.model]) {
        [CJUIKit showErrorWithStatus:@"请选择社区"];
    }else{
        
        [self showLoadingView];
        NSString *userId = [[CJUserInfoManager sharedManager] currentUserInfo].USERID;
        NSMutableArray *marr = [NSMutableArray new];
        for (NSInteger index = 0; index < _selectedPhotos.count; index ++) {
            NSData *imageData = UIImageJPEGRepresentation(_selectedPhotos[index], 0.8);
            [marr addObject:imageData];
        }
        
        
        NSDictionary *dic = @{
                              @"Userid": userId,
                              @"Text": str,
                              @"Shequnid": self.model.COMMUNITYID,
                              };
        
        if ([self.model.state isEqualToString:@"未加入"]) {
            if ([NSObject isNilOrNull:userId]) {
                userId = @"";
            }
            
            CJBaseRequest *request = [CJBaseRequest cj_requestWithUrl:[NSString stringWithFormat:@"%@/VEService/JoinShequn.do",kPublicInterfaceAPI] isPost:YES withParameters:@{@"shequnid":self.model.COMMUNITYID,@"Userid":userId}];
            [request cj_sendRequestWithCompletion:^(id response, BOOL success, NSString *message) {
                
                NSString *path = [NSString stringWithFormat:@"%@/VEService/AddCommentDynamic.do",kPublicInterfaceAPI];
                CJBaseRequest *request = [CJBaseRequest cj_requestWithUrl:path isPost:YES withParameters:dic];
                request.cj_imageArray =  marr;
                [request cj_sendRequestWithCompletion:^(id response, BOOL success, NSString *message) {
                    [self hideLoadingView];
                    NSLog(@"%@",response);
                    [CJUIKit showSuccessWithStatus:message];
                    [self.navigationController popViewControllerAnimated:YES];
                }];
                
            }];
        } else {
            
            NSString *path = [NSString stringWithFormat:@"%@/VEService/AddCommentDynamic.do",kPublicInterfaceAPI];
            CJBaseRequest *request = [CJBaseRequest cj_requestWithUrl:path isPost:YES withParameters:dic];
            request.cj_imageArray =  marr;
            [request cj_sendRequestWithCompletion:^(id response, BOOL success, NSString *message) {
                 [self hideLoadingView];
                NSLog(@"%@",response);
                [CJUIKit showSuccessWithStatus:message];
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)cj_numberOfSections {
    return 1;
}

/**
 某个cell的数量
 */
- (NSInteger)cj_numberOfRowsInsection:(NSInteger)section {
    return 2;
}

- (CGFloat)cj_cellHeightAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        return 142;
    } else if (indexPath.row == 1) {
        CGFloat PIC_HEIGHT = (kScreenWidth-6 *GAP8)/3;
        
        if (_seletedImgArr.count == 10) {
            NSInteger row = _seletedImgArr.count / 3;
            return (PIC_HEIGHT +10) * row + 10;
        }else{
            NSInteger row = _seletedImgArr.count / 3;
            if (_seletedImgArr.count % 3 == 0) {
                return (PIC_HEIGHT+10)*row+10;
            }else{
                return (PIC_HEIGHT+10)*(row+1)+10;
            }
        }
    } else {
        return 90;
    }
    
}

/**
 某行的cell
 */
- (CJBaseTableViewCell *)cj_cellAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        WEAKSELF
        VECreatDTSummaryTableViewCell *cell = [VECreatDTSummaryTableViewCell cellWithTableView:self.tableView];
        __weak typeof(cell) weakCell = cell;
        _inputTextView = cell.inputTextView;
        cell.seletedAssion = ^{
            VEAssociationViewController *vc= [VEAssociationViewController new];
            vc.isCrearDT = YES;
            vc.seletedAssionGetAssionId = ^(VEAssionModel *model) {
                weakSelf.model = model;
                [weakCell.button setTitle:model.COMMUNITYNAME forState:(UIControlStateNormal)];
            };
            [self.navigationController pushViewController:vc animated:YES];
        };

        return cell;
    } else {
        WEAKSELF
        VECreatDTImageTableViewCell *cell = [VECreatDTImageTableViewCell cellWithTableView:self.tableView];
        cell.imageArray = _seletedImgArr;
        cell.clickChoiceImage = ^(NSInteger tag) {
            [weakSelf choiceImg];

        };
        
        cell.clickDeleteImage = ^(NSInteger tag) {
            [self->_selectedPhotos removeObjectAtIndex:tag];
            self->_seletedImgArr = [self->_selectedPhotos copy];
            NSMutableArray * muArr = [self->_seletedImgArr mutableCopy];
            [muArr addObject:self->_nomalImg];
            self->_seletedImgArr = [muArr copy];
            [weakSelf.tableView reloadData];
            
        };
        return cell;
    }
    
}

#pragma mark - 选中上传图片
- (void)choiceImg
{
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:0 handler:^(UIAlertAction * _Nonnull action) {
        [self pushImagePickerController];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:0 handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
        BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];

        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}
#pragma mark - 拍照
- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied)) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        alert.delegate = self;
        [alert show];
        // 拍照之前还需要检查相册权限
    } 
    //    else if ([TZImageManager authorizationStatus] == 0) { // 正在弹框询问用户是否允许访问相册，监听权限状态
    //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //            return [self takePhoto];
    //        });
    //    }
    else { // 调用相机
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            self.imagePickerVc.sourceType = sourceType;
            _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;

            [self presentViewController:_imagePickerVc animated:YES completion:nil];
        } else {
            NSLog(@"模拟器中无法打开照相机,请在真机中使用");
        }
    }
}


#pragma mark - 选择照片
- (void)pushImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:KChoicePicCount-_selectedPhotos.count columnNumber:KLineShowPicCount delegate:self pushPhotoPickerVc:YES];
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = NO;
    
    if (KChoicePicCount > 1) {
        // 1.设置目前已经选中的图片数组
        imagePickerVc.selectedAssets = _selectedAssets; // 目前已经选中的图片数组
    }
    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
    
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingGif = NO;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVc.showSelectBtn = YES;
    imagePickerVc.allowCrop = NO;
    imagePickerVc.needCircleCrop = NO;
    imagePickerVc.circleCropRadius = 100;
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//        [_selectedAssets addObject:assetModel.asset];
        [_selectedPhotos addObject:image];
        
        _seletedImgArr = [_selectedPhotos copy];
        NSMutableArray * muArr = [_seletedImgArr mutableCopy];
        [muArr addObject:_nomalImg];
        _seletedImgArr = [muArr copy];
        
        [self.tableView reloadData];
        
    }
}

#pragma mark - TZImagePickerControllerDelegate

// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    for (id obj in photos) {
        [_selectedPhotos addObject:obj];
    }
    _seletedImgArr = [_selectedPhotos copy];
    NSMutableArray * muArr = [_seletedImgArr mutableCopy];
    [muArr addObject:_nomalImg];
    _seletedImgArr = [muArr copy];
    
    
    [self.tableView reloadData];
    
}



@end
